<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2015-8-25
 * Time: 10:13
 */

namespace common\components\services\message;

use common\models\datas\LoginAuth;
use common\models\datas\MessageLog;
use common\models\datas\Site;
use EasyWeChat\Foundation\Application;
use EasyWeChat\Message\Image;
use EasyWeChat\Message\Music;
use EasyWeChat\Message\News;
use EasyWeChat\Message\Video;
use EasyWeChat\Message\Voice;
use yii\base\BaseObject;
use yii\helpers\ArrayHelper;
use yii\helpers\Url;
use yii\web\NotFoundHttpException;
use common\components\helpers\Fun;

class   WechatMessage extends BaseObject
{
    const WECHAT_CUSTOM_MESSAGE_MASS_SEND_PREFIX = 'https://api.weixin.qq.com/cgi-bin/message/mass/send';

    public function send($id,$site_id = 0)
    {
        \Yii::$app->set('db', \Yii::$app->params['sys_back_db']);
        sleep(1);
        $item = MessageLog::findOne(['id'=>$id]);

        if ($item === null) {
            throw new NotFoundHttpException(\Yii::t('common', '信息不存在'));
        }
        $receiver = unserialize($item->receiver_arr);
        $site = Site::findOne($item->site_id);
        //同步wechat_auth
        $wechat_auth = LoginAuth::find()->where(['user_id' => $receiver,'web_site_id'=>$site->web_site_id])->asArray()->all();
        $openid = ArrayHelper::getColumn($wechat_auth, 'source_id');
        $options = \Yii::$app->params['options'];
        if($site->mode == 2){
            $options = \Yii::$app->params['options_zht'];
        }
        $messagetype = \Yii::$app->params['type'];
        $app = new Application($options);
        $content = $message = $item->content_wechat;
        $url = '';
        if(strpos($content,'<br>')){
            $arr = explode('<br>',$content);
            $message = $arr[0];
            $url = $arr[1];
        }
        if(count($openid) == 1){
           /* preg_match('/<a .*?href="(.*?)".*?>/is',$content,$match);
            $url = !empty($match)?$match[1]:'';
           */
            $news = new News([
                'title'       => $messagetype[$item->type_id]['name'],
                'description' => $message,
                'url'         => $url,
            ]);
            $result = $app->staff->message([$news])->to($openid[0])->send();
        }else{
            $broadcast = $app->broadcast;
            $result = $broadcast->send('text',$message,$openid);
        }
        //\Yii::error($result);
        if($result->errcode==0){
            $log_status=unserialize($item->status);
            $log_status['wechat']=1;
            $item->status = serialize($log_status);
            $item->save(false);
            return true;
        }else{
            return false;
        }
    }


    public function getResponsewechatmsg($replytype = 'noset',$data=null){
        switch($replytype){
            case 'text':
                if(!empty($data) && count($data) > 0){
                    return $data[0]['replytext'];
                    break;
                }else{
                    return '您好';
                    break;
                }
            case 'news':
                if(!empty($data)){
                    if(count($data) == 1){//单图文有摘要
                        $news = new News([
                            'title'       => htmlspecialchars($data[0]['replytext']),
                            'description' => htmlspecialchars($data[0]['replydescription']),//'豆苗朵“百万少儿素质教育启蒙工程”拥有岛城乃至全国知名的教育专家、导师团组成的优质师资团队。将提供3-12岁孩子免费的素质教育机会，您可任意选择和搭配声器乐类、形体舞蹈类、益智手工类等课程共100余个科目，让孩子在启蒙学习中选择出自己真正感兴趣的课程。',
                            'url'         => htmlspecialchars($data[0]['replyurl']),
                            'image'       => htmlspecialchars($data[0]['replyimgurl']),
                            // ...
                        ]);
                        return $news;
                    }else{
                        $num = 0;
                        $news_arr = [];
                        foreach($data as $val){//多图文没有摘要
                            //如果关注事件整了图文and音乐两种，如果是音乐 那data[0]没问题，但是如果data[0]是图文的类型，那将音乐的值付过来就有问题了，所以这里限制死
                            if($num < 10){
                                if($val['replytype'] == 'news'){
                                    $news = new News([
                                        'title'       => htmlspecialchars($val['replytext']),
                                        'description' => htmlspecialchars($val['replydescription']),//'豆苗朵“百万少儿素质教育启蒙工程”拥有岛城乃至全国知名的教育专家、导师团组成的优质师资团队。将提供3-12岁孩子免费的素质教育机会，您可任意选择和搭配声器乐类、形体舞蹈类、益智手工类等课程共100余个科目，让孩子在启蒙学习中选择出自己真正感兴趣的课程。',
                                        'url'         => htmlspecialchars($val['replyurl']),
                                        'image'       => htmlspecialchars($val['replyimgurl']),
                                    ]);
                                    $news_arr[] = $news;
                                    $num ++;
                                }
                            }else{
                                break;
                            }

                        }
                        return $news_arr;
                    }
                }
                break;
            case 'image':
                if(!empty($data) && count($data) > 0){
                    $text = new Image(['media_id' => $data[0]['wechat_media_id']]);
                    return $text;
                    break;
                }else{
                    return '您好';
                    break;
                }
            case 'voice':
                if(!empty($data) && count($data) > 0){
                    $text = new Voice(['media_id' => $data[0]['wechat_media_id']]);
                    return $text;
                    break;
                }else{
                    return '您好';
                    break;
                }
            case 'video':
                if(!empty($data) && count($data) > 0){
                    $video = new Video([
                        'title' => htmlspecialchars($data[0]['replytext']),
                        'media_id' => $data[0]['wechat_media_id'],
                        'description' => htmlspecialchars($data[0]['replydescription']),
                    ]);
                    return $video;
                    break;
                }else{
                    return '您好';
                    break;
                }
            case 'music':
                if(!empty($data) && count($data) > 0){
                    $music = new Music([
                        'title' => htmlspecialchars($data[0]['replytext']),
                        'url' => htmlspecialchars($data[0]['replymusic_url']),
                        'hq_url' => htmlspecialchars($data[0]['replyhqmusic_url']),
                        'thumb_media_id' => htmlspecialchars($data[0]['wechat_media_id']),
                        'description' => htmlspecialchars($data[0]['replydescription']),
                    ]);
                    return $music;
                    break;
                }else{
                    return '您好';
                    break;
                }
            default:
                return '您好';
                break;
        }
    }
}
